package com.example.JcGQS.util;

import cn.hutool.core.date.DateTime;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.example.JcGQS.exception.TokenException;

/**
 * JWT工具类
 * @author 末日
 * @date 2023/11/21
 */
public class JwtUtil {
    
    /**
     * SALT 盐
     */
    private static final String SALT = "JunChenRobotCompany";
    
    private static final long EXPIRATION_TIME = 7 * 24 * 60 * 60 * 1000;
    
    /**
     * 创建jwtToken
     *
     * @param userId
     *         用户id
     *
     * @return String
     */
    public static String createJwtToken(Integer userId) {
        // 过期时间
        DateTime expirationTIME = new DateTime(System.currentTimeMillis() + EXPIRATION_TIME);
        // 密匙加密
        Algorithm sercret = Algorithm.HMAC256(SALT);
        return JWT.create().withClaim("userId", userId).withExpiresAt(expirationTIME).sign(sercret);
    }

    public static void main(String[] args) {
        String jwtToken = JwtUtil.createJwtToken(1);

        System.out.println(jwtToken);
    }
    /**
     * 验证token是否合法
     *
     * @param token
     *         token
     *
     * @return boolean
     */
    public static boolean verify(String token) {
        // 密匙加密
        Algorithm algorithm = Algorithm.HMAC256(SALT);
        JWTVerifier verifier = JWT.require(algorithm).build();
        // 验证token
        try {
            verifier.verify(token);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return false;
        }
        return true;
    }
    
    /**
     * 根据token获取用户id
     *
     * @param token
     *         token
     *
     * @return Integer
     *
     * @throws JWTDecodeException
     *         jwt验证异常
     */
    public static Integer getUserIdByJWT(String token) throws JWTDecodeException {
        // 解密JWT
        return JWT.decode(token).getClaim("userId").asInt();
    }
    
}
